﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ZealousTTS.Domain;
using ZealousTTS.Web.ViewModels;
using AutoMapper;
using ZealousTTS.Common.Xml;
using ZealousTTS.Common.Extensions;
using ZealousTTS.Common.DB;
using System.IO;
using ZealousTTS.Common.Mail;

namespace ZealousTTS.Web.Utility
{
    public static class WebUtil
    {
        /// <summary>
        /// Populates the Session for an previously Authenticated User
        /// </summary>
        public static void ReLoginUser()
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated && SessionCache.CurrentUser == null)
            {
                String userName = HttpContext.Current.User.Identity.Name;
                ZealousTTSEntities context = new ZealousTTSEntities();
                User user = context.Users.FirstOrDefault(U => String.Compare(U.UserName, userName, true) == 0);                
                if (user != null)
                {
                    ///Load Group and Group Permissions                                
                    //user.UserGroup = groupDAO.Get(user.GroupCode);                
                    UserViewModel userViewModel = null;
                    userViewModel = Mapper.Map<User, UserViewModel>(user, userViewModel);

                    ///Load Compnay Information, if Exists
                    //LoadCompanyInfo(userViewModel, user, context);
                    SessionCache.CurrentUser = userViewModel;
                }
            }
        }
        /// <summary>
        /// Loads Company Information to the UserViewModel Object if user is a companys User
        /// </summary>
        /// <param name="userViewModel"></param>
        /// <param name="user"></param>
        /// <param name="context"></param>
        //public static void LoadCompanyInfo(UserViewModel userViewModel, User user, ZealousTTS.Domain.ZealousTTSEntities context)
        //{
        //    if (user.UserContacts.Count > 0)
        //    {
        //        UserContact userContact = context.UserContacts.FirstOrDefault(P => P.UserID == user.ID);
        //        if (userContact != null && userContact.Contact.Company != null)
        //        {
        //            Company company = userContact.Contact.Company;
        //            userViewModel.Company = Mapper.Map<Company, CompanyViewModel>(company);
        //        }
        //    }
        //}        
        public static String GetBooleanLabelID(String elementName, bool isEnabled)
        {
            if (isEnabled)
                return String.Format("{0}{1}_Yes", AppConstants.UI.DYNAMIC_CONTROL_PREFIX, elementName);
            else
                return String.Format("{0}{1}_No", AppConstants.UI.DYNAMIC_CONTROL_PREFIX, elementName);
        }

        public static bool IsTrue(String value)
        {
            return String.Compare(value, "Yes", true) == 0 ? true : false;
        }
        public static bool IsFalse(String value)
        {
            return String.Compare(value, "No", true) == 0 ? true : false;
        }        
        /// <summary>
        /// Gets Formated Data for Display Purpose
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static String FormatData(object data)
        {
            if (data.GetType() == typeof(String))
                return NullHandler.GetString(data);
            else if (data.GetType() == typeof(DateTime))
                return NullHandler.GetDateTime(data).ToString(AppConstants.ValueOf.DATE_FROMAT_DISPLAY);
            else if (data.GetType() == typeof(decimal))
                return String.Format(AppConstants.ValueOf.DECIMAL_FORMAT, NullHandler.GetDecimal(data));
            else if (data.GetType() == typeof(bool))
                return NullHandler.GetBoolean(data) ? "Yes" : "No";
            else
                return NullHandler.GetString(data);
        }
        /// <summary>
        /// Reads HTML Template from File System
        /// </summary>
        /// <param name="templateFileName"></param>
        /// <returns></returns>
        public static String ReadEmailTemplate(String templateFileName)
        {
            String filePath = HttpContext.Current.Server.MapPath(templateFileName);
            if (File.Exists(filePath))
                return File.ReadAllText(filePath);

            return String.Empty;
        }
        /// <summary>
        /// Gets Currently Hosted Domain Address
        /// </summary>
        /// <returns></returns>
        public static String GetDomainAddress()
        {
            Uri uri = HttpContext.Current.Request.Url;
            String url = String.Format("{0}{1}{2}{3}", uri.Scheme, Uri.SchemeDelimiter, uri.Host, uri.Port == 80 ? String.Empty : ":" + uri.Port);
            //return String.Format("http://{0}", HttpContext.Current.Request.Url.Host);
            return url;
        }
       public static bool SendMail(String fromEmail, String toEmail, String bcc, String cc, String subject, String message)
       //public static bool SendMail(String toEmail, String subject, String message)
        {
            bool isSent = false;
            try
            {
                isSent = MailManager.SendMail(toEmail, cc, bcc, fromEmail, subject, message);
                //isSent = MailManager.SendEmail(toEmail, subject, message);
                //isSent = MailManager.SendEmailThroughGmail(toEmail, fromEmail, subject, message);
            }
            catch (Exception ex)
            {
                ///Log Failed Message
                ZealousTTSEntities context = new ZealousTTSEntities();
                EmailMessage email = new EmailMessage();
                email.Subject = subject;
                email.FromEmail = fromEmail;
                email.ToEmail = toEmail;
                email.CC = cc;
                email.BCC = bcc;
                email.Message = message;
                email.IsSent = false;
                email.Created = DateTime.Now;
                email.AttemptedOn = DateTime.Now;
                email.ErrorMessage = ex.Message;
                email.StackTrace = ex.StackTrace;
                if (SessionCache.CurrentUser != null)
                    email.UserID = SessionCache.CurrentUser.ID;
                context.AddToEmailMessages(email);
                context.SaveChanges();
            }
            return isSent;
        }

        /// <summary>
        /// Gets Product Dynamic Property Value from a Prepopulated Dynamic Property Collection
        /// </summary>
        /// <param name="groupName"></param>
        /// <param name="propertyName"></param>
        /// <param name="product"></param>
        /// <returns></returns>
        public static String GetPropertyValue(String groupName, String propertyName, ViewModels.LGL.Category.Category dynamicProperties)
        {
            if (dynamicProperties != null && dynamicProperties.Group != null)
            {
                ViewModels.LGL.Category.ProductGroup group = dynamicProperties.Group.FirstOrDefault(G => G.Name == groupName);
                if (group != null)
                {
                    ViewModels.LGL.Category.ProductGroupProperty property = group.Property.FirstOrDefault(P => P.Name == propertyName);
                    if (property != null)
                        return property.Value;
                }
            }
            return "N/A";
        }
    }
}